package com.wmh.baseservice.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.controller.SmsController;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.shiro.jwt.JwtTokenUtil;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.SignDecodeUtil;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.PageSortRoles;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.pojo.MerchantVegetablePlot;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantVegetablePlotService;
import com.wmh.baseservice.system.pojo.SysMessage;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysMessageService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.*;
import com.wmh.baseservice.user.pojo.vo.UsInfoRespVO;
import com.wmh.baseservice.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Api(tags = "用户端-个人中心相关接口")
@RestController
@RequestMapping(value = "user/info", produces = "text/plain;charset=utf-8")
//@RequiresRoles("user")
public class UsInfoController {

    @Resource
    private UsJoinApplyService usJoinApplyService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsVegetableOrderService usVegetableOrderService;
    @Resource
    private UsGoodsOrderService usGoodsOrderService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private SmsController smsController;
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private UsAfterSaleApplyService usAfterSaleApplyService;
    @Resource
    private UsParentOrderService usParentOrderService;

    @ApiOperation("是否完善个人信息")
    @PostMapping("hasInfo")
    public String hasInfo() {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (!CommUtil.checkNull(usInfo.getPhone(), usInfo.getName())) {
            return ReturnBody.success(false);
        }
        return ReturnBody.success(true);
    }

    @ApiOperation("个人信息")
    @PostMapping("info")
    public String info() {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        JSONObject object = new JSONObject(true);
        object.put("phone", usInfo.getPhone());
        object.put("name", usInfo.getName());
        object.put("balance", usInfo.getBalance());
        return ReturnBody.success(object);
    }

    @ApiOperation("入驻申请")
    @PostMapping("joinApply")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = "所属人姓名", required = true),
            @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", required = true),
            @ApiImplicitParam(paramType = "query", name = "lng", value = "经度", required = true),
            @ApiImplicitParam(paramType = "query", name = "lat", value = "维度", required = true),
            @ApiImplicitParam(paramType = "query", name = "address", value = "地址", required = true),
            @ApiImplicitParam(paramType = "query", name = "businessType", value = "0只可摘菜 1只可种菜 2全支持", required = true),
            @ApiImplicitParam(paramType = "query", name = "hasPartner", value = "是否有合伙人 0个体 1有合伙人", required = true),
            @ApiImplicitParam(paramType = "query", name = "province", value = "省", required = true),
            @ApiImplicitParam(paramType = "query", name = "city", value = "市", required = true),
            @ApiImplicitParam(paramType = "query", name = "area", value = "区", required = true),
            @ApiImplicitParam(paramType = "query", name = "partnerInfo", value = "合伙人信息,json数组，里面的json对象为合伙人，最多2个", required = false, example = "[{\"shares\":0.43,\"nick\":\"C.C.\",\"phone\":\"1366666666\",\"name\":\"林俊杰\",\"avatar\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJObxMINf3FMMyict5XxflUibAQnZia1HdcjibgSYlWyBUaMXcumEVKrPMm6KAHziaEHq5lgc0Vdz9SZKw/132\",\"usId\":5},{\"shares\":0.33,\"nick\":\"测试用户账号\",\"phone\":\"13531788703\",\"name\":\"测试用户账号\",\"avatar\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/MQqhgQhkK2nv35tTQ4Qzw1RkJAOkQ5FffMsibTjtysiaLJg0Gm0G3WkoA049vx1gVaH9BsxSMklZ4KPQGkJpl9Gg/132\",\"usId\":6}]"),
    })
    @ParameterVerify(notNull = {"name", "phone"})
    public String joinApply(String name, String phone, String lng, String lat, String address, Integer businessType, Integer hasPartner, String province, String city,
                            String area, String partnerInfo, String storeAvatar, String storeName) {
        Long usId = (Long) request.getAttribute("usId");
        //重复提交校验
        UsJoinApply rawJoin = usJoinApplyService.getOneForUpdate(new QueryWrapper<UsJoinApply>().eq(UsJoinApply.STATUS, 0).eq(UsJoinApply.US_ID, usId));
        if (CommUtil.checkNull(rawJoin)) {
            return ReturnBody.error("您有一个申请正在审核中，请不要重复提交");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        List<MerchantInfo> merchant = merchantInfoService.listForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.ACCOUNT, usInfo.getPhone()));
        if (CommUtil.checkNull(merchant) && merchant.size() != 0) {
            return ReturnBody.error(usInfo.getPhone() + "手机号已被其他商家注册，请到我的账户处重新绑定手机号后再提交申请");
        }
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usInfo.getMerchantId());
            if (merchantInfo.getType() == 1) {
                return ReturnBody.error("您已经是商家了，请不要重复申请");
            }
        }
        if (!CommUtil.checkNull(usInfo.getPhone(), usInfo.getName())) {
            return ReturnBody.error("您还未完善手机号和真实姓名，请移步至个人中心完善");
        }

        UsJoinApply usJoinApply;
        if (businessType == 3) {
            //TODO 无土地
            String image = Base64Util.generateImage("goodsM/", storeAvatar);
            if (!CommUtil.checkNull(image)) {
                return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
            }
            usJoinApply = new UsJoinApply().setUsId(usId).setType(businessType).setShopName(CommUtil.checkNull(storeName) ? storeName : "默认店铺名称")
                    .setShopStore(image).setName(name).setPhone(phone).setHasPartner(0);
        } else {
            //TODO 有土地
            //参数处理
            usJoinApply = new UsJoinApply().setUsId(usId).setHasPartner(hasPartner).setName(name).setStatus(0).setProvince(province).setCity(city).setArea(area).setAddress(address)
                    .setLat(lat).setLon(lng).setPhone(phone).setType(businessType);
            if (CommUtil.checkNull(partnerInfo) && hasPartner == 1) {
                JSONArray array = JSONArray.parseArray(partnerInfo);
                //去重
                Set set = new HashSet(array);
                array = JSONArray.parseArray(set.toString());
                if (array.size() == 0 || array.size() > 2) {
                    return ReturnBody.error("合伙人最少1个最多2个");
                }

                JSONObject parent = new JSONObject(true);
                BigDecimal max = BigDecimal.ONE;
                JSONArray newArray = new JSONArray();

                //校验
                array.forEach(item -> {
                    JSONObject object = JSONObject.parseObject(item.toString());
                    Long sonUsId = object.getLong("usId");
                    UsInfo sonUsInfo = usInfoService.getByIdForUpdate(sonUsId);
                    if (!sonUsId.equals(usId)) {
                        if (CommUtil.checkNull(sonUsInfo.getMerchantId())) {
                            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(sonUsInfo.getMerchantId());
                            if (merchantInfo.getType() == 1) {
                                throw new ServiceException("合伙人" + sonUsInfo.getNick() + "已是商家");
                            }
                        }
                    }
                    Object shares2 = object.remove("shares2");
                    if (CommUtil.checkNull(shares2)) {
                        object.put("shares", shares2);
                    }
                    newArray.add(object);
                });

                //分配收益占比
                final BigDecimal[] sum = {BigDecimal.ZERO};
                newArray.forEach(item -> {
                            JSONObject peopleObj = JSONObject.parseObject(item.toString());
                            if (CommUtil.checkNull(peopleObj.getBigDecimal("shares2"))) {
                                sum[0] = sum[0].add(peopleObj.getBigDecimal("shares2"));
                            }
                            if (CommUtil.checkNull(peopleObj.getBigDecimal("shares"))) {
                                sum[0] = sum[0].add(peopleObj.getBigDecimal("shares"));
                            }
                        }
                );
                if (sum[0].compareTo(max) >= 0) {
                    return ReturnBody.error("权益占比大于100%,请重新输入（合伙人收益占比加起来不能超过或等于1）");
                }
                parent.put("shares", max.subtract(sum[0]));
                parent.put("nick", usInfo.getNick());
                parent.put("phone", usInfo.getPhone());
                parent.put("name", usInfo.getName());
                parent.put("avatar", usInfo.getAvatar());
                parent.put("usId", usInfo.getId());
                newArray.add(parent);
                usJoinApply.setPartnerInfo(newArray.toJSONString());
            }
        }
        if (!usJoinApplyService.save(usJoinApply)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        //发送短信通知
        try {
            smsController.sendCode("13531788702", usInfo.getPhone());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return ReturnBody.success();
    }

    @ApiOperation("合伙人查询")
    @PostMapping("phoneSelect")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", required = true),
    })
    @ParameterVerify(notNull = "phone")
    public String phoneSelect(String phone) {
        Long usId = (Long) request.getAttribute("usId");
        List<UsInfo> usInfos = usInfoService.listForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.PHONE, phone).select(UsInfo.NAME, UsInfo.ID, UsInfo.NICK, UsInfo.PHONE, UsInfo.AVATAR, UsInfo.MERCHANT_ID));
        if (usInfos.size() != 1) {
            return ReturnBody.error("获取用户信息错误，请确保该用户登录过小程序并且已在个人中心完善过手机号和真实姓名");
        }
        UsInfo usInfo = usInfos.get(0);
        if (usInfo.getId().equals(usId)) {
            return ReturnBody.error("请勿填写自己");
        }
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            return ReturnBody.error("该用户已是商家");
        }
        if (!CommUtil.checkNull(usInfo.getName())) {
            return ReturnBody.error("请到个人中心完善真实姓名");
        }
        return ReturnBody.success(usInfo);
    }

    @ApiOperation("完善信息")
    @PostMapping("perfectInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"name", "phone", "phoneCode", "codeKey"})
    public String perfectInfo(String name, String phone, String phoneCode, String codeKey) {
        JSONObject verifyResult = SignDecodeUtil.codeMatches(phoneCode, codeKey, 300000);
        if (!verifyResult.getBoolean("isSuccess")) {
            return ReturnBody.error(ResultCodeInfo.SMS_CODE_ERROR);
        }
        Long usId = (Long) request.getAttribute("usId");
        UsInfo rawUsInfo = usInfoService.getOneForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.PHONE, phone));
        if (CommUtil.checkNull(rawUsInfo)) {
            return ReturnBody.error("该手机号已被绑定");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        usInfo.setName(name).setPhone(phone);
        if (!usInfoService.updateById(usInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }

        return ReturnBody.success();
    }

    @ApiOperation("修改用户姓名")
    @PostMapping("updateUserName")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "name", value = "用户姓名", required = false)
    })
    @ParameterVerify(notNull = "name")
    public String updateUserName(String name) {
        Long usId = (Long) request.getAttribute("usId");
        if (!usInfoService.update(new UpdateWrapper<UsInfo>().eq(UsInfo.ID, usId).set(UsInfo.NAME, name))) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("订单列表")
    @PostMapping("orderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "0待付款 1已付款 3已评价 -1已取消", required = true),
    })
    public String orderList(PageInfo pageInfo, Integer status) {
        Long usId = (Long) request.getAttribute("usId");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);

        //执行分页辅助工具
        PageResult<UsVegetableOrder> pageResult = new PageUtil<UsVegetableOrder>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsVegetableOrder.US_ID, usId);
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsVegetableOrder.STATUS, status);
            }
            usVegetableOrderService.page(page, queryWrapper);
        });

        //执行分页辅助工具
//        PageResult<UsParentOrder> pageResult = new PageUtil<UsParentOrder>(pageInfo).startPage((page, queryWrapper) -> {
//            queryWrapper.eq(UsVegetableOrder.US_ID, usId);
//            if (CommUtil.checkNull(status)) {
//                queryWrapper.eq(UsVegetableOrder.STATUS, status);
//            }
//            usParentOrderService.page(page, queryWrapper);
//        });
        JSONArray orderList = new JSONArray();
        pageResult.getList().forEach(item -> {
            JSONObject object = new JSONObject();
            //查询是否有父订单
            UsParentOrder usParentOrder = usParentOrderService.getOne(new QueryWrapper<UsParentOrder>().like(UsParentOrder.SON_ORDER, item.getOrderNum()));
            if (!CommUtil.checkNull(usParentOrder)) {
                //单个购买订单
                object.put("son", item);
            } else {
                object.put("parentOrder", item.getOrderNum());
                object.put("status", item.getStatus());
                JSONArray son = JSONArray.parseArray(usParentOrder.getSonOrder());
                JSONArray array = new JSONArray();
                son.forEach(order -> {
                    UsVegetableOrder usVegetableOrder = usVegetableOrderService.getOne(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, order.toString()));
                    if (CommUtil.checkNull(usVegetableOrder)) {
                        array.add(usVegetableOrder);
                    }
                });
                object.put("son", array);
            }
            if (item.getAfterSalesStatus() == 1) {
                object.put("afterSalesStatus", item.getAfterSalesStatus());
            }
            orderList.add(object);
        });
        PageResult orderResult = new PageResult<>().setList(orderList).setPageNo(pageResult.getPageNo()).setPages(pageResult.getPages()).setTotal(pageResult.getTotal()).
                setPageSize(pageResult.getPageSize());
        return ReturnBody.success(orderResult);
    }

    @ApiOperation("订单详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String detail(String orderNum) {
        JSONObject object = new JSONObject(true);
        Long usId = (Long) request.getAttribute("usId");
        UsVegetableOrder usVegetableOrder = usVegetableOrderService.getOneForUpdate(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, orderNum));
        if (!CommUtil.checkNull(usVegetableOrder) || !usVegetableOrder.getUsId().equals(usId)) {
            return ReturnBody.error("订单错误");
        }
        //查询商家信息
        MerchantInfo info = merchantInfoService.getByIdForUpdate(usVegetableOrder.getMerchantId());
        //查询土地信息
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getOneForUpdate(
                new QueryWrapper<MerchantVegetablePlot>().select(
                        MerchantVegetablePlot.LAT, MerchantVegetablePlot.LNG, MerchantVegetablePlot.ADDRESS,
                        MerchantVegetablePlot.GROW_OPEN_TIME, MerchantVegetablePlot.GROW_OVER_TIME,
                        MerchantVegetablePlot.PICK_OPEN_TIME, MerchantVegetablePlot.PICK_OVER_TIME
                )
                        .eq(MerchantVegetablePlot.ID, usVegetableOrder.getPlotId())
        );
        object.put("plotDetail", merchantVegetablePlot);
        object.put("storeAvatar", info.getStoreAvatar());
        object.put("storeName", info.getStoreName());
        object.put("phone", info.getPhone());
        object.put("order", usVegetableOrder);
        return ReturnBody.success(object);
    }

    @ApiOperation("取消订单")
    @PostMapping("cancelOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String cancelOrder(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsVegetableOrder usVegetableOrder = usVegetableOrderService.getOneForUpdate(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, orderNum));
        if (!CommUtil.checkNull(usVegetableOrder) || !usVegetableOrder.getUsId().equals(usId) || usVegetableOrder.getStatus() != 0) {
            return ReturnBody.error("订单状态错误");
        }
        usVegetableOrder.setStatus(-1);
        if (!usVegetableOrderService.updateById(usVegetableOrder)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("商品订单列表")
    @PostMapping("shopOrderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String shopOrderList(PageInfo pageInfo, Integer status) {
        Long usId = (Long) request.getAttribute("usId");
        //执行分页辅助工具
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsGoodsOrder> pageResult = new PageUtil<UsGoodsOrder>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsGoodsOrder.STATUS, status);
            queryWrapper.eq(UsGoodsOrder.US_ID, usId);
            usGoodsOrderService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(item.getMerchantId());
            if (CommUtil.checkNull(merchantInfo)) {
                item.setStoreAvatar(merchantInfo.getStoreAvatar());
                item.setStoreName(merchantInfo.getStoreName());
            }
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("商品订单详情")
    @PostMapping("shopOrderDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单号", required = true),
    })
    @ParameterVerify(notNull = {"orderNum"})
    public String shopOrderDetail(String orderNum) {
        JSONObject object = new JSONObject(true);
        Long usId = (Long) request.getAttribute("usId");
        UsGoodsOrder usGoodsOrder = usGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGoodsOrder>().eq(UsGoodsOrder.ORDER_NUM, orderNum).eq(UsGoodsOrder.US_ID, usId));
        if (!CommUtil.checkNull(usGoodsOrder)) {
            return ReturnBody.error("订单不存在");
        }
        object.put("order", usGoodsOrder);
        //店铺信息
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usGoodsOrder.getMerchantId());
        if (CommUtil.checkNull(merchantInfo)) {
            object.put("type", 1);
            object.put("storeAvatar", merchantInfo.getStoreAvatar());
            object.put("storeName", merchantInfo.getStoreName());
            object.put("storePhone", merchantInfo.getPhone());
        } else {
            object.put("type", 2);
            SysParams sysParams = sysParamsService.getByIdForUpdate(4L);
            if (!CommUtil.checkNull(sysParams)) {
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
            object.put("phone", sysParams.getValue());
        }
        return ReturnBody.success(object);
    }

    @ApiOperation("我的消息")
    @PostMapping("myMessage")
    public String myMessage(PageInfo pageInfo) {
        Long usId = (Long) request.getAttribute("usId");
        PageSortRoles pageSortRoles = new PageSortRoles();
        pageSortRoles.putPageSortRoles(SysMessage.STATUS, SysMessage.STATUS, SortWay.ASC);
        pageSortRoles.putPageSortRoles(SysMessage.CREATE_TIME, SysMessage.CREATE_TIME, SortWay.DESC);
        pageInfo.setPageSortRoles(pageSortRoles);
        //执行分页辅助工具
        PageResult<SysMessage> pageResult = new PageUtil<SysMessage>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(SysMessage.US_ID, usId);
            queryWrapper.select(SysMessage.TITLE, SysMessage.CONTENT, SysMessage.STATUS, SysMessage.ID, SysMessage.US_ID, SysMessage.CREATE_TIME);
            sysMessageService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("未读消息数")
    @PostMapping("unRead")
    public String unRead() {
        Long usId = (Long) request.getAttribute("usId");
        int count = sysMessageService.count(new QueryWrapper<SysMessage>().eq(SysMessage.US_ID, usId).eq(SysMessage.STATUS, 0));
        return ReturnBody.success(count);
    }

    @ApiOperation("一键已读")
    @PostMapping("allRead")
    public String allRead() {
        Long usId = (Long) request.getAttribute("usId");
        UpdateWrapper<SysMessage> updateWrapper = new UpdateWrapper<SysMessage>().set(SysMessage.STATUS, 1).eq(SysMessage.US_ID, usId);
        if (!sysMessageService.update(updateWrapper)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("已读")
    @PostMapping("read")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String msgList(Long id) {
        Long usId = (Long) request.getAttribute("usId");
        UpdateWrapper<SysMessage> updateWrapper = new UpdateWrapper<SysMessage>().set(SysMessage.STATUS, 1).eq(SysMessage.US_ID, usId).eq(SysMessage.ID, id);
        if (!sysMessageService.update(updateWrapper)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("查询商家账号")
    @PostMapping("selectAccount")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String selectAccount() {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        String account = "";
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usInfo.getMerchantId());
            account = merchantInfo.getAccount();
        }

        return ReturnBody.success(account);
    }

    @ApiOperation("我邀请的用户")
    @PostMapping("myUserList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String myUserList(PageInfo pageInfo) {
        Long usId = (Long) request.getAttribute("usId");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsInfo> pageResult = new PageUtil<UsInfo>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsInfo.INVITE_ID, usId).select(UsInfo.ID, UsInfo.AVATAR, UsInfo.NICK, UsInfo.CREATE_TIME, UsInfo.MERCHANT_ID);
            usInfoService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("推广参数")
    @PostMapping("reParam")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String reParam() {
        SysParams costParam = sysParamsService.getByIdForUpdate(16L);
        SysParams moneyParam = sysParamsService.getByIdForUpdate(15L);
        JSONObject object = new JSONObject(true);
        object.put("cost", costParam.getValue());
        object.put("money", moneyParam.getValue());
        return ReturnBody.success(object);
    }

    @ApiOperation("个人中心提醒")
    @PostMapping("mineNotice")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String mineNotice() {
        Long usId = (Long) request.getAttribute("usId");
        JSONObject object = new JSONObject(true);
        object.put("sendGroupOrder", 0);
        object.put("refundGroupOrder", 0);
        //团购查询是否有已发货订单
        int sendCount = usGroupGoodsOrderService.count(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.STATUS, 2)
                .eq(UsGroupGoodsOrder.US_ID, usId));
        if (sendCount >= 1) {
            object.put("sendGroupOrder", sendCount);
        }
        //团购查询是否有已退款待寄回订单
        int refundCount = usAfterSaleApplyService.count(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.US_ID, usId).eq(UsAfterSaleApply.STATUS, 1)
                .eq(UsAfterSaleApply.TYPE, 2));
        if (refundCount >= 1) {
            object.put("refundGroupOrder", refundCount);
        }
        return ReturnBody.success(object);
    }

    @ApiIgnore
    @ApiOperation("审核状态(微信审核用)")
    @PostMapping("auditStatus")
    public String auditStatus() {
        Long usId = (Long) request.getAttribute("usId");
        SysParams hasJoin = sysParamsService.getByIdForUpdate(9L);
        SysParams hasRent = sysParamsService.getByIdForUpdate(10L);
        JSONObject object = new JSONObject(true);
        object.put("hasRent", hasRent.getValue());
        object.put("hasJoin", hasJoin.getValue());
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (CommUtil.checkNull(usInfo)) {
            object.put("hasMerchant", CommUtil.checkNull(usInfo.getMerchantId()) ? -1 : 0);
        }
        return ReturnBody.success(object);
    }

    @ApiIgnore
    @ApiOperation("绑定微信公众号openId")
    @PostMapping("bindMpOpenId")
    @ParameterVerify(notNull = "mpOpenId")
    public String bindMpOpenId(String mpOpenId) {
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (!CommUtil.checkNull(usInfo.getMpOpenId())) {
            usInfo.setMpOpenId(mpOpenId);
            if (!usInfoService.updateById(usInfo)) {
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
        }
        return ReturnBody.success();
    }

}
